package com.hd.crdao.activity;

import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.Handler;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.PopupWindow;

import com.google.gson.Gson;
import com.hd.crdao.R;
import com.hd.crdao.base.BaseSecondActivity;
import com.hd.crdao.bean.MsgBean;
import com.hd.crdao.config.Config;
import com.hd.crdao.config.Constants;
import com.hd.crdao.utils.ALog;
import com.hd.crdao.utils.MyToast;
import com.hd.crdao.utils.SPUtils;
import com.hd.crdao.utils.UIUtils;
import com.hd.crdao.view.ExpandHeadView;
import com.hd.crdao.wrapper.GlideImageUtils;
import com.hss01248.dialog.StyledDialog;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

import butterknife.BindView;
import butterknife.OnClick;
import okhttp3.Call;

/**
 * @author Programming
 * @date 2017/5/22 0022
 */
public class ChangeHeadPicActivity extends BaseSecondActivity {
    private static final int FROM_CAMERA = 100;
    private static final int FROM_PIC = 101;
    private static final int SENDPIC_OK = 102;
    @BindView(R.id.changeheadpic)
    ExpandHeadView mChangeheadpic;
    @BindView(R.id.largeImage)
    ImageView mLargeImage;
    @BindView(R.id.takePicture)
    Button mTakePicture;


    @Override
    protected void initView() {
        initEvent();
    }

    @Override
    protected int setContentView() {
        return R.layout.activity_changeheadpic;
    }

    @Override
    protected ExpandHeadView setExpandHeadView() {
        return mChangeheadpic;
    }

    private void initEvent() {
        mChangeheadpic.getHeadViewRightText().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //保存图片操作
               /* Intent intent = new Intent();
                intent.putExtra("headimagespath", mCurrentPhotoPath);
                setResult(SENDPIC_OK, intent);
                finish();*/
                StyledDialog.buildLoading().setActivity(ChangeHeadPicActivity.this).show();
                upLoadImage();
            }


        });

    }

    /**
     * 上传头像到服务器
     */
    private void upLoadImage() {
        Handler handler = new Handler();
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                if (TextUtils.isEmpty(mCurrentPhotoPath)) {
                    return;
                }
                String busnissid = SPUtils.getString(Config.businessId, "");
                OkHttpUtils.post().url(Constants.CHANGECARBUSINESS_URL)
                        .addParams("sign", Constants.SIGN)
                        .addParams("appFlag", "true")
                        .addParams("id", busnissid)
                        .addFile("cbImage", mCurrentPhotoPath, new File(mCurrentPhotoPath))
                        .build().execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        MyToast.show("网络开了个小差");
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        ALog.d(response);
                        MsgBean msgBean = new Gson().fromJson(response, MsgBean.class);
                        if (msgBean.getSuccess() == 0) {
                            MyToast.show("保存成功");
                            startActivity(new Intent(UIUtils.getContext(), UserActivity.class));
                            finish();
                        } else {
                            MyToast.show(msgBean.getMessage());
                        }
                        StyledDialog.dismissLoading();
                    }
                });
            }
        }, 2000);


    }

    @OnClick({R.id.largeImage, R.id.takePicture})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.largeImage:
                //点击会放大图片操作
                // Intent intent = new Intent(UIUtils.getContext(), ViewBigPicActivity.class);
                //  startActivity(intent);
                break;
            case R.id.takePicture:
                showCameraPopwidow();
                break;
        }
    }


    /**
     * //弹出有拍照图库的popupwindow 和它的点击事件处理
     */
    private void showCameraPopwidow() {
        View parent = ((ViewGroup) this.findViewById(android.R.id.content)).getChildAt(0);
        View popView = View.inflate(this, R.layout.camera_pop_menu, null);

        Button btnCamera = (Button) popView.findViewById(R.id.btn_camera_pop_camera);
        Button btnAlbum = (Button) popView.findViewById(R.id.btn_camera_pop_album);
        Button btnCancel = (Button) popView.findViewById(R.id.btn_camera_pop_cancel);

        int width = getResources().getDisplayMetrics().widthPixels;
        int height = getResources().getDisplayMetrics().heightPixels;

        final PopupWindow popWindow = new PopupWindow(popView, width, height);
        popWindow.setAnimationStyle(R.style.AnimBottom);
        popWindow.setFocusable(true);
        popWindow.setOutsideTouchable(true);// 设置允许在外点击消失
        ColorDrawable dw = new ColorDrawable(0x30000000);
        popWindow.setBackgroundDrawable(dw);
        popWindow.showAtLocation(parent, Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);


        View.OnClickListener listener = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                switch (v.getId()) {
                    case R.id.btn_camera_pop_camera:
                        pickPicFromCam();   //从相机中获取图片
                        break;
                    case R.id.btn_camera_pop_album:
                        pickPicFromPic();//从图库中获取图片
                        break;
                    case R.id.btn_camera_pop_cancel:
                        break;
                    default:
                        break;
                }
                popWindow.dismiss();


            }
        };

        btnCamera.setOnClickListener(listener);
        btnAlbum.setOnClickListener(listener);
        btnCancel.setOnClickListener(listener);


    }

    /**
     * 从拍照获取图片
     */
    private void pickPicFromCam() {

        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        File imageFile;
        Uri pictureUri;
        try {
            imageFile = createImageFile();
            if (imageFile != null) {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                    ContentValues contentValues = new ContentValues(1);
                    contentValues.put(MediaStore.Images.Media.DATA, imageFile.getAbsolutePath());
                    pictureUri = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues);
                } else {
                    intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                    pictureUri = Uri.fromFile(imageFile);
                }
                intent.putExtra(MediaStore.EXTRA_OUTPUT,
                        pictureUri);
                startActivityForResult(intent, FROM_CAMERA);

            }
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    /**
     * 从图库获取图片 经调试OK
     */
    private void pickPicFromPic() {
        Intent intent;
        if (Build.VERSION.SDK_INT < 19) {
            intent = new Intent(Intent.ACTION_GET_CONTENT);
            intent.setType("image/*");
        } else {
            intent = new Intent(
                    Intent.ACTION_PICK,
                    android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        }
        startActivityForResult(intent, FROM_PIC);

    }

    private String mCurrentPhotoPath;

    /**
     * 创建image文件的路径
     *
     * @return
     * @throws IOException
     */
    private File createImageFile() throws IOException {
        if (!Environment.getExternalStorageState().equals(
                Environment.MEDIA_MOUNTED)) {
            MyToast.show("SD卡不可用");
        } else {
            String pre = new SimpleDateFormat("yyyy_MM_dd_hh_mm_ss_SSS", Locale.CHINESE)
                    .format(new Date());
            //创建图片保存的位置
            File path = new File(Environment.getExternalStorageDirectory(),
                    "myImage");
            //如果路径不存在
            if (!path.exists()) {
                //创建路径，需要权限
                path.mkdirs();
            }
            //组合全部的路径
            mCurrentPhotoPath = path.toString() + File.separator + pre + ".jpg";
            SPUtils.saveString("headphotopath", mCurrentPhotoPath);
            ALog.d(mCurrentPhotoPath);
            return new File(mCurrentPhotoPath);

        }

        return null;
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        //相机中获取图片
        if (requestCode == FROM_CAMERA && resultCode == RESULT_OK) {
            GlideImageUtils.loadImage(mCurrentPhotoPath, R.drawable.logo_moren_2x, true, mLargeImage);

           /* Glide.with(UIUtils.getContext()).load(mCurrentPhotoPath)
                    .bitmapTransform(new GlideCircleTransform(UIUtils.getContext()))
                    .placeholder(R.drawable.logo_moren_2x).into(mLargeImage);*/
        }
        //从图库选择返回的结果
        if (requestCode == FROM_PIC && resultCode == RESULT_OK) {
            Uri selectedImage = data.getData();
            String[] filePathColumn = {MediaStore.Images.Media.DATA};

            Cursor cursor = null;
            if (selectedImage != null) {
                cursor = getContentResolver().query(selectedImage,
                        filePathColumn, null, null, null);
            }
            assert cursor != null;
            cursor.moveToFirst();
            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
            mCurrentPhotoPath = cursor.getString(columnIndex);
            SPUtils.saveString("headphotopath", mCurrentPhotoPath);
            cursor.close();
            GlideImageUtils.loadImage(mCurrentPhotoPath, R.drawable.logo_moren_2x, true, mLargeImage);
           /* Glide.with(UIUtils.getContext()).load(mCurrentPhotoPath)
                    .bitmapTransform(new GlideCircleTransform(UIUtils.getContext()))
                    .placeholder(R.drawable.logo_moren_2x).into(mLargeImage);*/
            ALog.d(mCurrentPhotoPath);

        }
        super.onActivityResult(requestCode, resultCode, data);
    }


    /**
     * 压缩图片
     */
    private void setImageBitmap(ImageView imageView, String photoPath) {
        //获取imageview的宽和高
        int targetWidth = imageView.getWidth();
        int targetHeight = imageView.getHeight();

        //根据图片路径，获取bitmap的宽和高
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(photoPath, options);
        int photoWidth = options.outWidth;
        int photoHeight = options.outHeight;

        //获取缩放比例
        int inSampleSize = 1;
        if (photoWidth > targetWidth || photoHeight > targetHeight) {
            int widthRatio = Math.round((float) photoWidth / targetWidth);
            int heightRatio = Math.round((float) photoHeight / targetHeight);
            inSampleSize = Math.min(widthRatio, heightRatio);
        }

        //使用现在的options获取Bitmap
        options.inSampleSize = inSampleSize;
        options.inJustDecodeBounds = false;
        Bitmap bitmap = BitmapFactory.decodeFile(photoPath, options);
        imageView.setImageBitmap(bitmap);
    }


    @Override
    public void onBackPressed() {
        super.onBackPressed();
        startActivity(new Intent(UIUtils.getContext(), UserActivity.class));
        finish();
    }
}